<template>
    <div class="traceability-detail-container">
        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 右上角操作按钮区域 -->
            <div class="top-right-actions">
                <el-button type="danger" class="action-btn">
                    <el-icon class="action-icon">
                        <Lightning />
                    </el-icon>
                    删除
                </el-button>
                <el-button type="primary" class="action-btn">
                    <el-icon class="action-icon">
                        <Lightning />
                    </el-icon>
                    修改基本信息
                </el-button>
                <el-button type="primary" class="action-btn">
                    <el-icon class="action-icon">
                        <Lightning />
                    </el-icon>
                    导出溯源码
                </el-button>
            </div>

            <!-- 左侧商品信息区域 -->
            <div class="product-section">
                <!-- 商品图片区域 -->
                <div class="product-image-container">
                    <img :src="form.picture || '/default-product.jpg'" alt="商品图片" class="product-image" />
                    <div class="product-logo">
                        <div class="logo-icon">🐰</div>
                        <span class="logo-text">爱吃兔</span>
                    </div>
                </div>

                <!-- 商品基本信息 -->
                <div class="product-info">
                    <h2 class="product-name">{{ getProductName() || '兔头 (麻辣味)' }}</h2>
                    <div class="product-details">
                        <div class="detail-item">
                            <span class="detail-label">生产批次:</span>
                            <span class="detail-value">{{ form.batch || '20210718' }}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">保质期:</span>
                            <span class="detail-value">{{ form.expiration ? form.expiration + '天' : '90天' }}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">生产许可证号:</span>
                            <span class="detail-value">{{ form.license || 'SC213205427680' }}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">生产企业:</span>
                            <span class="detail-value">{{ form.company || '成都爱吃兔食品加工有限公司' }}</span>
                        </div>
                    </div>
                </div>

                <!-- 产品检验报告区域 -->
                <div class="inspection-reports">
                    <h3 class="section-title">产品检验报告</h3>
                    <div class="reports-container">
                        <!-- 显示已上传的报告图片 -->
                        <div class="report-item" v-for="(imageUrl, index) in getReportImages()" :key="index">
                            <img :src="imageUrl" alt="检验报告" class="report-thumbnail" @click="previewImage(index)" />
                            <el-icon class="remove-icon" @click="removeReport(index)">
                                <Close />
                            </el-icon>
                        </div>
                        <!-- 上传按钮 -->
                        <div class="report-uploader">
                            <el-upload :file-list="fileList"
                                action="http://localhost:5124/api/WriteBasic/UploadMultiple" list-type="picture-card"
                                name="files" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                                :on-success="handleUploadSuccess" :on-error="handleUploadError"
                                :before-upload="beforeUpload" :multiple="true" :limit="5">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </div>
                        <div class="report-uploader">
                            <el-button type="primary" @click="savePictureData">保存图片</el-button>

                        </div>
                    </div>
                </div>
            </div>
<div>
    <!-- dsa -->
</div>
            <!-- 右侧表单区域 -->
        </div>

        <!-- 新增底部卡片组件 -->
        <div class="bottom-card">
            <div class="card-header">
                <h3 class="card-title">溯源信息管理</h3>
            </div>
            <div class="card-content">
                <!-- 顶部状态指示器 -->
                <div class="status-indicators">
                    <div class="status-item"
                        :class="{ 'active': showBreedingInfo, 'incomplete breeding': !showBreedingInfo }"
                        @click="showBreedingInfoContent">
                        <div class="status-icon"></div>
                        <span class="status-text">养殖信息 ({{ completedBreedingSections }}/5)</span>
                    </div>
                    <div class="status-item"
                        :class="{ 'active': showSlaughterInfo, 'incomplete slaughter': !showSlaughterInfo }"
                        @click="showSlaughterInfoContent">
                        <div class="status-icon"></div>
                        <span class="status-text">屠宰信息 (5/5)</span>
                    </div>
                    <div class="status-item incomplete processing">
                        <div class="status-icon"></div>
                        <span class="status-text">深加工信息 (0/5)</span>
                    </div>
                </div>

                <!-- 主要内容区域 -->
                <div class="main-content-grid">
                    <!-- 养殖信息区域 -->
                    <div v-if="showBreedingInfo" class="breeding-section">
                        <div class="left-column">
                            <div class="info-section">
                                <div class="section-header">
                                    <span class="section-title">养殖信息</span>
                                    <el-button type="success" @click="fantian" size="small" class="settings-btn"
                                        style="margin-left: 8px;">
                                        <el-icon>
                                            <Refresh />
                                        </el-icon>
                                        设置
                                    </el-button>
                                </div>
                                <div class="section-content">
                                    <!-- 养殖信息内容 -->
                                    <div class="cultivation-info">
                                        <!-- 横向排列的信息网格 -->
                                        <div class="info-grid">
                                            <div class="info-item">
                                                <div class="info-label">品种</div>
                                                <div class="info-value">{{ detail.variety || '暂无数据' }}</div>
                                            </div>
                                            <div class="info-item">
                                                <div class="info-label">来源</div>
                                                <div class="info-value">{{ detail.source || '暂无数据' }}</div>
                                            </div>
                                            <div class="info-item">
                                                <div class="info-label">养殖天数</div>
                                                <div class="info-value">{{ detail.rearingDays || '暂无数据' }}</div>
                                            </div>
                                            <div class="info-item">
                                                <div class="info-label">品牌</div>
                                                <div class="info-value">{{ detail.brand || '暂无数据' }}</div>
                                            </div>
                                            <div class="info-item">
                                                <div class="info-label">养殖负责人</div>
                                                <div class="info-value">{{ detail.rearingLeader || '暂无数据' }}</div>
                                            </div>
                                            <div class="info-item">
                                                <div class="info-label">出栏日期</div>
                                                <div class="info-value">{{ detail.outDate || '暂无数据' }}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 免疫信息 -->
                            <div class="info-section">
                                <div class="section-header">
                                    <span class="section-title">免疫信息</span>
                                    <div class="header-actions">
                                        <span class="add-row-text" @click="addImmunityRow">新增行</span>
                                    </div>
                                </div>
                                <div class="section-content">
                                    <!-- 免疫信息内容 -->
                                    <div class="immunity-info" v-if="immunityRows.length > 0">
                                        <div class="immunity-rows">
                                            <div class="immunity-row" v-for="(row, index) in immunityRows" :key="index">
                                                <div class="row-header">
                                                    <span class="row-title">免疫记录 {{ index + 1 }}</span>
                                                    <div class="row-actions">
                                                        <el-button type="success" size="small"
                                                            @click="saveSingleImmunityRow(index)" class="save-row-btn">
                                                            <el-icon>
                                                                <Check />
                                                            </el-icon>
                                                            保存
                                                        </el-button>
                                                        <el-button type="primary" size="small"
                                                            @click="updateImmunityRow(index)" class="save-row-btn">
                                                            <el-icon>
                                                                <Check />
                                                            </el-icon>
                                                            修改
                                                        </el-button>
                                                        <el-button type="danger" size="small"
                                                            @click="removeImmunityRow(index)" class="remove-row-btn">
                                                            <el-icon>
                                                                <Close />
                                                            </el-icon>
                                                            删除
                                                        </el-button>
                                                    </div>
                                                </div>
                                                <div class="immunity-grid">
                                                    <div class="immunity-item">
                                                        <div class="immunity-label">养殖天数</div>
                                                        <div class="immunity-value">
                                                            <el-input v-model="row.rearingDays" placeholder="请输入养殖天数"
                                                                size="small" @blur="saveImmunityRow(index)" />
                                                        </div>
                                                    </div>
                                                    <div class="immunity-item">
                                                        <div class="immunity-label">免疫方式</div>
                                                        <div class="immunity-value">
                                                            <el-input v-model="row.way" placeholder="请输入免疫方式"
                                                                size="small" @blur="saveImmunityRow(index)" />
                                                        </div>
                                                    </div>
                                                    <div class="immunity-item">
                                                        <div class="immunity-label">免疫功能</div>
                                                        <div class="immunity-value">
                                                            <el-input v-model="row.function" placeholder="请输入免疫功能"
                                                                size="small" @blur="saveImmunityRow(index)" />
                                                        </div>
                                                    </div>
                                                    <div class="immunity-item">
                                                        <div class="immunity-label">批次号</div>
                                                        <div class="immunity-value">
                                                            <el-input v-model="row.batch" placeholder="请输入批次号"
                                                                size="small" @blur="saveImmunityRow(index)" />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div v-else class="no-data">
                                        <el-icon class="no-data-icon">
                                            <Document />
                                        </el-icon>
                                        <span class="no-data-text">暂无免疫信息数据，点击"新增行"添加</span>
                                    </div>
                                </div>
                            </div>

                            <!-- 动检证 -->
                            <div class="info-section">
                                <div class="section-header">
                                    <span class="section-title">动检证</span>
                                </div>
                                <div class="section-content">
                                    <div class="reports-container">
                                        <!-- 显示动检证图片 -->
                                        <div class="report-item" v-for="(imageUrl, index) in getInspectionImages()"
                                            :key="index">
                                            <img :src="imageUrl" alt="动检证" class="report-thumbnail"
                                                @click="previewInspectionImage(index)" />
                                            <el-icon class="remove-icon" @click="removeInspectionImage(index)">
                                                <Close />
                                            </el-icon>
                                        </div>
                                        <!-- 上传按钮 -->
                                        <div class="report-uploader">
                                            <el-upload :action="uploadAction" :headers="uploadHeaders"
                                                :show-file-list="false" :on-success="handleInspectionSuccess"
                                                :before-upload="beforeUpload" :http-request="customUpload"
                                                accept="image/*" multiple>
                                                <div class="report-placeholder">
                                                    <el-icon class="add-icon">
                                                        <Plus />
                                                    </el-icon>
                                                </div>
                                            </el-upload>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 企业信息 -->
                            <div class="info-section">
                                <div class="section-header">
                                    <span class="section-title">企业信息</span>
                                    <el-button @click="companylist()" type="primary" size="small" class="settings-btn">
                                        <el-icon>
                                            <Lightning />
                                        </el-icon>
                                        设置
                                    </el-button>
                                </div>
                                <div class="section-content">
                                    <div
                                        style="display: flex; justify-content: space-around; align-items: center; padding: 16px 0;">
                                        <div
                                            style="flex: 1; text-align: center; padding: 0 8px; display: flex; flex-direction: column; align-items: center;">
                                            <div style="font-weight: 500; color: #606266; margin-bottom: 4px;">养殖场
                                            </div>
                                            <div style="color: #303133;">{{ companyDetail1.farm }}</div>
                                        </div>
                                        <div
                                            style="flex: 1; text-align: center; padding: 0 8px; display: flex; flex-direction: column; align-items: center;">
                                            <div style="font-weight: 500; color: #606266; margin-bottom: 4px;">负责人
                                            </div>
                                            <div style="color: #303133;">{{ companyDetail1.leader }}</div>
                                        </div>
                                        <div
                                            style="flex: 1; text-align: center; padding: 0 8px; display: flex; flex-direction: column; align-items: center;">
                                            <div style="font-weight: 500; color: #606266; margin-bottom: 4px;">保存方式
                                            </div>
                                            <div style="color: #303133;">{{ companyDetail1.saves }}</div>
                                        </div>
                                        <div
                                            style="flex: 1; text-align: center; padding: 0 8px; display: flex; flex-direction: column; align-items: center;">
                                            <div style="font-weight: 500; color: #606266; margin-bottom: 4px;">批次号
                                            </div>
                                            <div style="color: #303133;">{{ companyDetail1.batch }}</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 企业照片 -->
                            <div class="info-section">
                                <div class="section-header">
                                    <span class="section-title">企业照片</span>
                                </div>
                                <div class="section-content">
                                    <div class="reports-container">
                                        <!-- 显示企业照片图片 -->
                                        <div class="report-item" v-for="(imageUrl, index) in getCultivationImages()"
                                            :key="index">
                                            <img :src="imageUrl" alt="企业照片" class="report-thumbnail"
                                                @click="previewCultivationImage(index)" />
                                            <el-icon class="remove-icon" @click="removeCultivationImage(index)">
                                                <Close />
                                            </el-icon>
                                        </div>
                                        <!-- 上传按钮 -->
                                        <div class="report-uploader">
                                            <el-upload :action="uploadAction" :headers="uploadHeaders"
                                                :show-file-list="false" :on-success="handleCultivationSuccess"
                                                :before-upload="beforeUpload" :http-request="customUpload"
                                                accept="image/*" multiple>
                                                <div class="report-placeholder">
                                                    <el-icon class="add-icon">
                                                        <Plus />
                                                    </el-icon>
                                                </div>
                                            </el-upload>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 屠宰信息区域 -->
                    <div v-if="showSlaughterInfo" class="slaughter-section">
                        <div class="left-column">
                            <div class="info-section">
                                <div class="section-header">
                                    <span class="section-title">屠宰信息</span>
                                    <el-button type="success" @click="tuzaiDetailsshezhi" size="small"
                                        class="settings-btn" style="margin-left: 8px;">
                                        <el-icon>
                                            <Refresh />
                                        </el-icon>
                                        设置
                                    </el-button>
                                </div>
                                <div class="section-content">
                                    <div class="info-grid">
                                        <div class="info-item">
                                            <div class="info-label">批次</div>
                                            <div class="info-value">{{ tuzaiDetail1.batch || '暂无数据' }}</div>
                                        </div>
                                        <div class="info-item">
                                            <div class="info-label">到厂均重(公斤)</div>
                                            <div class="info-value">{{ tuzaiDetail1.weight || '暂无数据' }}</div>
                                        </div>
                                        <div class="info-item">
                                            <div class="info-label">到厂时间</div>
                                            <div class="info-value">{{ tuzaiDetail1.startTime || '暂无数据' }}</div>
                                        </div>
                                        <div class="info-item">
                                            <div class="info-label">屠宰时间</div>
                                            <div class="info-value">{{ tuzaiDetail1.endTime || '暂无数据' }}</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 相关资质信息 -->
                            <div class="info-section">
                                <div class="section-header">
                                    <span class="section-title">相关资质</span>
                                </div>
                                <div class="section-content">
                                    <div class="reports-container">
                                        <!-- 显示相关资质图片 -->
                                        <div class="report-item" v-for="(imageUrl, index) in getAptitudeImages()"
                                            :key="index">
                                            <img :src="imageUrl" alt="相关资质" class="report-thumbnail"
                                                @click="previewAptitudeImage(index)" />
                                            <el-icon class="remove-icon" @click="removeAptitudeImage(index)">
                                                <Close />
                                            </el-icon>
                                        </div>
                                        <!-- 上传按钮 -->
                                        <div class="report-uploader">
                                            <el-upload :action="uploadAction" :headers="uploadHeaders"
                                                :show-file-list="false" :on-success="handleAptitudeSuccess"
                                                :before-upload="beforeUpload" :http-request="customUpload"
                                                accept="image/*" multiple>
                                                <div class="report-placeholder">
                                                    <el-icon class="add-icon">
                                                        <Plus />
                                                    </el-icon>
                                                </div>
                                            </el-upload>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 企业信息(屠宰) -->
                            <div class="info-section">
                                <div class="section-header">
                                    <span class="section-title">企业信息(屠宰)</span>
                                    <el-button type="success" @click="openSlaughterCompanyDialog" size="small"
                                        class="settings-btn" style="margin-left: 8px;">
                                        <el-icon>
                                            <Refresh />
                                        </el-icon>
                                        设置
                                    </el-button>
                                </div>
                                <div class="section-content">
                                    <div class="info-grid">
                                        <div class="info-item">
                                            <div class="info-label">公司名称</div>
                                            <div class="info-value">{{ slaughterCompanyData.companyName || '暂无数据' }}
                                            </div>
                                        </div>
                                        <div class="info-item">
                                            <div class="info-label">公司地址</div>
                                            <div class="info-value">{{ slaughterCompanyData.address || '暂无数据' }}</div>
                                        </div>
                                        <div class="info-item">
                                            <div class="info-label">公司描述</div>
                                            <div class="info-value">{{ slaughterCompanyData.companyDesc || '暂无数据' }}
                                            </div>
                                        </div>
                                        <div class="info-item">
                                            <div class="info-label">成立时间</div>
                                            <div class="info-value">{{ slaughterCompanyData.establish || '暂无数据' }}</div>
                                        </div>
                                        <div class="info-item">
                                            <div class="info-label">批次号</div>
                                            <div class="info-value">{{ slaughterCompanyData.batch || '暂无数据' }}</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 企业照片(屠宰) -->
                            <div class="info-section">
                                <div class="section-header">
                                    <span class="section-title">企业照片(屠宰)</span>
                                </div>
                                <div class="section-content">
                                    <div class="reports-container">
                                        <!-- 显示屠宰企业照片 -->
                                        <div class="report-item"
                                            v-for="(imageUrl, index) in getSlaughterPictureImages()" :key="index">
                                            <img :src="imageUrl" alt="屠宰企业照片" class="report-thumbnail"
                                                @click="previewSlaughterPictureImage(index)" />
                                            <el-icon class="remove-icon" @click="removeSlaughterPictureImage(index)">
                                                <Close />
                                            </el-icon>
                                        </div>
                                        <!-- 上传按钮 -->
                                        <div class="report-uploader">
                                            <el-upload :action="uploadAction" :headers="uploadHeaders"
                                                :show-file-list="false" :on-success="handleSlaughterPictureSuccess"
                                                :before-upload="beforeUpload" :http-request="customUpload"
                                                accept="image/*" multiple>
                                                <div class="report-placeholder">
                                                    <el-icon class="add-icon">
                                                        <Plus />
                                                    </el-icon>
                                                </div>
                                            </el-upload>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 图片预览对话框 -->
                <el-dialog v-model="previewVisible" title="产品检验报告" width="auto" center>
                    <div class="image-preview-container">
                        <!-- 左箭头 -->
                        <div class="nav-arrow nav-left" @click="prevImage"
                            :class="{ disabled: currentImageIndex === 0 }">
                            <el-icon>
                                <ArrowLeft />
                            </el-icon>
                        </div>

                        <!-- 图片显示区域 -->
                        <div class="image-display-area">
                            <img :src="currentImageUrl" alt="检验报告预览" class="preview-image"
                                @touchstart="handleTouchStart" @touchmove="handleTouchMove"
                                @touchend="handleTouchEnd" />
                        </div>

                        <!-- 右箭头 -->
                        <div class="nav-arrow nav-right" @click="nextImage"
                            :class="{ disabled: currentImageIndex === inspectionReports.length - 1 }">
                            <el-icon>
                                <ArrowRight />
                            </el-icon>
                        </div>
                    </div>

                    <!-- 分页指示器 -->
                    <div class="pagination-dots">
                        <div v-for="(report, index) in inspectionReports" :key="index" class="dot"
                            :class="{ active: index === currentImageIndex }" @click="goToImage(index)"></div>
                    </div>

                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="previewVisible = false">关闭</el-button>
                            <el-button type="primary" @click="downloadImage">下载图片</el-button>
                        </div>
                    </template>
                </el-dialog>
                <!-- 养殖信息弹窗 -->
                <el-dialog v-model="dialogFormVisible" title="养殖信息设置" width="600px" center>
                    <el-form :model="detail" label-width="120px">
                        <el-form-item label="品种">
                            <el-input v-model="detail.variety" placeholder="请输入品种" />
                        </el-form-item>
                        <el-form-item label="来源">
                            <el-input v-model="detail.source" placeholder="请输入来源" />
                        </el-form-item>
                        <el-form-item label="养殖天数">
                            <el-input v-model="detail.rearingDays" placeholder="请输入养殖天数" />
                        </el-form-item>
                        <el-form-item label="品牌">
                            <el-input v-model="detail.brand" placeholder="请输入品牌" />
                        </el-form-item>
                        <el-form-item label="养殖负责人">
                            <el-input v-model="detail.rearingLeader" placeholder="请输入养殖负责人" />
                        </el-form-item>
                        <el-form-item label="出栏日期">
                            <el-date-picker v-model="detail.outDate" type="date" placeholder="请选择出栏日期"
                                style="width: 100%" />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="saveCultivationInfo">
                                保存
                            </el-button>
                        </div>
                    </template>
                </el-dialog>
                <!-- 免疫信息修改 -->
                <el-dialog v-model="updateImmunityRowdialogFormVisible" title="免疫信息修改" width="500">
                    <el-form :model="form">
                        <el-form-item label="饲养天数">
                            <el-input v-model="updateImmunityRowform.rearingDays" placeholder="请输入饲养天数" />
                        </el-form-item>
                        <el-form-item label="来源">
                            <el-input v-model="updateImmunityRowform.way" placeholder="请输入来源" />
                        </el-form-item>
                        <el-form-item label="免疫方式">
                            <el-input v-model="updateImmunityRowform.function" placeholder="请输入养殖天数" />
                        </el-form-item>
                        <el-form-item label="生产批次">
                            <el-input v-model="updateImmunityRowform.batch" placeholder="请输入生产批次" />
                        </el-form-item>

                    </el-form>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="updateImmunityRowlist">
                                确认
                            </el-button>
                        </div>
                    </template>
                </el-dialog>
                <!-- 屠宰信息修改 -->
                <el-dialog v-model="SlaughterdialogFormVisible" title="屠宰信息修改" width="500">
                    <el-form :model="tuzaiDetail1">
                        <el-form-item label="批次">
                            <el-input v-model="tuzaiDetail1.batch" placeholder="请输入批次" />
                        </el-form-item>
                        <el-form-item label="到厂均重(公斤)">
                            <el-input v-model="tuzaiDetail1.weight" placeholder="请输入重量" />
                        </el-form-item>
                        <el-form-item label="到厂时间">
                            <el-input v-model="tuzaiDetail1.startTime" placeholder="请输入到厂时间" />
                        </el-form-item>
                        <el-form-item label="屠宰时间">
                            <el-input v-model="tuzaiDetail1.endTime" placeholder="请输入屠宰时间" />
                        </el-form-item>

                    </el-form>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="SlaughterdialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="saveSlaughterInfo">
                                确认
                            </el-button>
                        </div>
                    </template>
                </el-dialog>
                <!-- 养殖信息企业信息反填 -->
                <el-dialog v-model="updateImmunityRowdialogFormVisible1" title="免疫信息修改" width="500">
                    <el-form :model="tuzaiDetail1">
                        <el-form-item label="批次">
                            <el-input v-model="tuzaiDetail1.batch" placeholder="请输入批次" />
                        </el-form-item>
                        <el-form-item label="到厂均重(公斤)">
                            <el-input v-model="tuzaiDetail1.weight" placeholder="请输入重量" />
                        </el-form-item>
                        <el-form-item label="到厂时间">
                            <el-input v-model="tuzaiDetail1.startTime" placeholder="请输入负责人" />
                        </el-form-item>
                        <el-form-item label="屠宰时间">
                            <el-input v-model="tuzaiDetail1.endTime" placeholder="请输入存栏次数" />
                        </el-form-item>


                    </el-form>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="updateImmunityRowlist">
                                确认
                            </el-button>
                        </div>
                    </template>
                </el-dialog>
                <!-- 屠宰企业信息弹窗 -->
                <el-dialog v-model="slaughterCompanyDialogVisible" title="屠宰企业信息" width="600px" center>
                    <el-form :model="slaughterCompanyData" label-width="120px">
                        <el-form-item label="公司名称">
                            <el-input v-model="slaughterCompanyData.companyName" placeholder="请输入公司名称" />
                        </el-form-item>
                        <el-form-item label="公司地址">
                            <el-input v-model="slaughterCompanyData.address" placeholder="请输入公司地址" />
                        </el-form-item>
                        <el-form-item label="公司描述">
                            <el-input v-model="slaughterCompanyData.companyDesc" placeholder="请输入公司描述" />
                        </el-form-item>
                        <el-form-item label="成立时间">
                            <el-input v-model="slaughterCompanyData.establish" placeholder="请输入成立时间" />
                        </el-form-item>
                        <el-form-item label="批次号">
                            <el-input v-model="slaughterCompanyData.batch" placeholder="请输入批次号" />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="slaughterCompanyDialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="saveSlaughterCompanyInfo">
                                保存
                            </el-button>
                        </div>
                    </template>
                </el-dialog>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'

import { read } from '@/Until/axiosHepler'
import { ElMessage } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import { ArrowDown, ArrowRight, Lightning, Close, Plus, Delete, Edit, ArrowLeft, Refresh, Document, Check } from '@element-plus/icons-vue'
const currentRoute = useRoute()
const store = useCounterStore();
const stores = useCounterStore();
const route = useRoute()
const productData = ref<any>({})
const currentTime = ref('')
const previewVisible1 = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
import { tread, twrite } from '@/Until/axiosHepler'
const SlaughterdialogFormVisible = ref(false)
const updateImmunityRowdialogFormVisible = ref(false)
import type { UploadProps } from 'element-plus'
import axios from 'axios'
const updateImmunityRowdialogFormVisible1 = ref(false)
const slaughterCompanyDialogVisible = ref(false)
const companylist = () => {
    updateImmunityRowdialogFormVisible1.value = true
}

// 打开屠宰企业信息弹窗
const openSlaughterCompanyDialog = () => {
    slaughterCompanyDialogVisible.value = true
}

// 保存屠宰企业信息
const saveSlaughterCompanyInfo = () => {
    console.log('保存屠宰企业信息:', slaughterCompanyData.value)
    ElMessage.success('屠宰企业信息保存成功')
    slaughterCompanyDialogVisible.value = false
}
const Pic = reactive({
    "batch": "string",
    "report": [],
    "inspection": "string",
    "cultivationPicture": "string",
    "aptitude": "string",
    "slaughterPicture": "string",
    "safe": "string",
    "raw": "string",
    "accessories": "string",
    "additive": "string",
    "package": "string",
    "deepPicture": "string"
})
//保存图片
const savePictureData = () => {
    twrite.post('/api/WriteBasic/AddPic', Pic).then((res) => {
        console.log('保存图片响应:', res)
        if (res.data.code == 200) {
            ElMessage.success(res.data.message || '保存成功')
        } else {
            ElMessage.error(res.data.message || '保存失败')
        }

    })
}

const tuzaiDetailsshezhi = () => {
    SlaughterdialogFormVisible.value = true
}

// 保存屠宰信息
const saveSlaughterInfo = () => {
    console.log('保存屠宰信息:', tuzaiDetail1.value)

    // 这里可以添加保存到后端的逻辑
    // 例如：调用API保存屠宰信息
    // twrite.post('/api/Slaughter/UpdateSlaughter', tuzaiDetail1.value).then((res) => {
    //     if (res.data.code == 200) {
    //         ElMessage.success(res.data.message || '保存成功')
    //         SlaughterdialogFormVisible.value = false
    //     } else {
    //         ElMessage.error(res.data.message || '保存失败')
    //     }
    // }).catch((error) => {
    //     console.error('保存屠宰信息失败:', error)
    //     ElMessage.error('保存失败: ' + error.message)
    // })

    // 临时显示成功消息
    ElMessage.success('屠宰信息保存成功')
    SlaughterdialogFormVisible.value = false
}
// 上传错误处理
const handleUploadError = (error: any, file: any) => {
    console.error('上传失败:', error)
    console.error('失败文件:', file)
    ElMessage.error('图片上传失败: ' + (error.message || '网络错误'))
}


// 上传成功回调
const handleUploadSuccess = (response: any, file: any) => {
    console.log('上传成功响应:', response)
    console.log('上传文件信息:', file)

    // 检查服务器响应是否成功
    if (response && response.code !== 200) {
        console.error('服务器上传失败:', response.message)
        ElMessage.error('图片上传失败：' + (response.message || '服务器返回错误'))
        return
    }

    // 处理多图片上传响应 - 根据Swagger API格式
    let imageUrls: string[] = []

    if (response && response.code === 200) {
        if (Array.isArray(response.data) && response.data.length > 0) {
            // 后端返回的是URL数组
            imageUrls = response.data
            console.log('从response.data数组获取图片URLs:', imageUrls)
        } else if (response.data && typeof response.data === 'string') {
            // 后端返回的是单个URL字符串
            imageUrls = [response.data]
            console.log('从response.data字符串获取图片URL:', response.data)
        } else {
            console.warn('response.data为空或格式不正确:', response.data)
        }
    } else if (response && response.success === true) {
        // 兼容其他可能的响应格式
        if (Array.isArray(response.data) && response.data.length > 0) {
            imageUrls = response.data
        } else if (response.data) {
            imageUrls = [response.data]
        }
    } else if (typeof response === 'string' && response.startsWith('http')) {
        imageUrls = [response]
    } else if (response && response.url) {
        imageUrls = [response.url]
    }

    // if (imageUrls.length > 0) {
    //     // 将新上传的图片URL添加到现有图片数组中
    //     picturelist.report = [...picturelist.reportpicture, ...imageUrls]
    //     console.log('图片URL已保存到form.picture:', form.picture)
    //     ElMessage.success(`图片上传成功，已保存${imageUrls.length}张图片`)
    // } else {
    //     console.error('无法从响应中提取图片URL:', response)
    //     console.error('响应结构分析:')
    //     console.error('- response类型:', typeof response)
    //     console.error('- response.code:', response?.code)
    //     console.error('- response.data:', response?.data)
    //     console.error('- response.message:', response?.message)
    //     ElMessage.error('图片上传失败：无法获取图片地址')
    // }
}
const fileList = ref<any[]>([])
const tuzaiDetail1 = ref({
    "batch": "",
    "weight": '',
    "startTime": "",
    "endTime": "",
    "id": 0,
    "isDeleted": false
})
//屠宰反填信息
const tuzaiDetails = () => {
    tread.get("/api/Slaughter/SlaughterDetail", { params: { batch: batch.value } }).then((res) => {
        console.log('屠宰信息API响应:', res.data)
        Object.assign(tuzaiDetail1.value, res.data.data)
    })
}


// 控制信息区域显示状态
const showBreedingInfo = ref(false)
const showSlaughterInfo = ref(false)

// 显示养殖信息
const showBreedingInfoContent = () => {
    showBreedingInfo.value = true
    showSlaughterInfo.value = false
}

// 显示屠宰信息
const showSlaughterInfoContent = () => {
    showBreedingInfo.value = false
    showSlaughterInfo.value = true
}

// 计算已完成的部分数量
const completedBreedingSections = computed(() => {
    let count = 0

    // 1. 养殖信息 - 检查是否有数据
    if (detail.value.variety || detail.value.source || detail.value.rearingDays ||
        detail.value.brand || detail.value.rearingLeader || detail.value.outDate) {
        count++
    }

    // 2. 免疫信息 - 检查是否有数据
    if (immunityRows.value && immunityRows.value.length > 0) {
        count++
    }

    // 3. 动检证 - 检查是否有图片
    if (picturelist.inspection && picturelist.inspection !== '') {
        count++
    }

    // 4. 企业信息 - 检查是否有数据
    if (companyDetail1.value.farm || companyDetail1.value.leader ||
        companyDetail1.value.saves || companyDetail1.value.batch) {
        count++
    }

    // 5. 企业照片 - 检查是否有图片
    if (picturelist.cultivationPicture && picturelist.cultivationPicture.length > 0) {
        count++
    }

    return count
})
//钩子函数
onMounted(() => {
    getCurrentTime()
    // 先加载商品列表，再获取详情
    storelist()
    Detail()
    yangzhidetails() // 加载养殖信息详情
    Immunitylist()//免疫信息
    pictureDetail();//图片反填
    companyDetail()//养殖企业反填
    tuzaiDetails()//屠宰信息反填
    slaughterCompanyDetail()//屠宰企业信息反填
})
//养殖企业反填
const companyDetail1 = ref({
    "farm": "",
    "leader": "",
    "saves": '',
    "batch": "",
    "id": 0,
    "isDeleted": false
})

//屠宰企业信息
const slaughterCompanyData = ref({
    "companyName": "",
    "address": "",
    "companyDesc": "",
    "establish": "",
    "batch": "",
    "id": 0,
    "isDeleted": false
})
const companyDetail = () => {
    tread.get("/api/Cultivation/CultivationCommpanyDeatil", { params: { batch: batch.value } }).then((res) => {
        console.log('养殖企业API响应:', res.data)
        Object.assign(companyDetail1.value, res.data.data)
    })
}

//屠宰企业信息反填
const slaughterCompanyDetail = () => {
    tread.get("/api/Slaughter/SlaughterCommpanyDetail", { params: { Batch: batch.value } }).then((res) => {
        console.log('屠宰企业信息API响应:', res.data)
        Object.assign(slaughterCompanyData.value, res.data.data)
    })
}
//图片反填
const picturelist = reactive({
    "batch": "",
    "report": "",
    "inspection": "",
    "cultivationPicture": [] as string[], // 明确指定为字符串数组类型
    "aptitude": [] as string[], // 修改为数组类型以支持多个图片URL
    "slaughterPicture": [] as string[],
    "safe": "",
    "raw": "",
    "accessories": "",
    "additive": "",
    "package": "",
    "deepPicture": "",
    "id": '',
    "isDeleted": false
})
const updateImmunityRowform = ref({
    "id": 0,
    "rearingDays": 0,
    "way": "string",
    "function": "string",
    "batch": "string"
})
//修改免疫信息
const updateImmunityRowlist = () => {
    // 根据Swagger API文档，PUT请求需要在请求体中发送数据
    const requestData = {
        id: updateImmunityRowform.value.id,
        rearingDays: parseInt(updateImmunityRowform.value.rearingDays.toString()) || 0,
        way: updateImmunityRowform.value.way,
        function: updateImmunityRowform.value.function,
        batch: updateImmunityRowform.value.batch
    }

    console.log('修改免疫信息请求数据:', requestData)

    twrite.put("/api/WriteBasic/UpdateImmunity", requestData).then((res) => {
        console.log('修改免疫信息响应:', res)
        if (res.data.code == 200) {
            ElMessage.success(res.data.message || '修改成功')
            console.log('修改免疫信息成功:', updateImmunityRowform.value)

            // 更新本地数据
            const index = immunityRows.value.findIndex(row => row.id === updateImmunityRowform.value.id)
            if (index !== -1) {
                Object.assign(immunityRows.value[index], requestData)
            }

            updateImmunityRowdialogFormVisible.value = false
        } else {
            ElMessage.error(res.data.message || '修改失败')
        }
    }).catch((error) => {
        console.error('修改免疫信息失败:', error)
        ElMessage.error('修改失败: ' + (error.response?.data?.message || error.message))
    })
}
//免疫信息弹出框
const updateImmunityRow = (index: number) => {
    // 获取选中的免疫信息行数据
    const selectedRow = immunityRows.value[index]
    if (selectedRow) {
        // 回显数据到表单
        updateImmunityRowform.value = {
            id: selectedRow.id || 0,
            rearingDays: selectedRow.rearingDays || 0,
            way: selectedRow.way || "",
            function: selectedRow.function || "",
            batch: selectedRow.batch || ""
        }
        console.log('回显免疫信息数据:', updateImmunityRowform.value)
        updateImmunityRowdialogFormVisible.value = true
    } else {
        ElMessage.error('未找到要修改的免疫信息')
    }
}
// 解析图片路径字符串为数组
const parseImageUrls = (imageString: string) => {
    if (!imageString) return []

    try {
        // 尝试解析JSON格式
        const parsed = JSON.parse(imageString)
        if (Array.isArray(parsed)) {
            return parsed.filter(url => url && typeof url === 'string' && url.startsWith('http'))
        }
    } catch (e) {
        // 如果不是JSON格式，当作单个URL处理
        if (typeof imageString === 'string' && imageString.startsWith('http')) {
            return [imageString]
        }
    }

    return []
}

// 获取检验报告图片列表
const getReportImages = () => {
    return parseImageUrls(picturelist.report)
}

// 获取动检证图片列表
const getInspectionImages = () => {
    return parseImageUrls(picturelist.inspection)
}

// 获取企业照片图片列表
const getCultivationImages = () => {
    // 处理CultivationPicture字段，它可能是数组或字符串
    if (Array.isArray(picturelist.cultivationPicture)) {
        // 如果直接是数组，直接返回
        return picturelist.cultivationPicture.filter(url => url && typeof url === 'string' && url.startsWith('http'))
    } else if (typeof picturelist.cultivationPicture === 'string') {
        // 如果是字符串，尝试解析
        return parseImageUrls(picturelist.cultivationPicture)
    }
    return []
}

// 获取相关资质图片列表
const getAptitudeImages = () => {
    // 处理aptitude字段，它可能是数组或字符串
    if (Array.isArray(picturelist.aptitude)) {
        // 如果直接是数组，直接返回
        return picturelist.aptitude.filter(url => url && typeof url === 'string' && url.startsWith('http'))
    } else if (typeof picturelist.aptitude === 'string') {
        // 如果是字符串，尝试解析
        return parseImageUrls(picturelist.aptitude)
    }
    return []
}

// 获取屠宰企业照片图片列表
const getSlaughterPictureImages = () => {
    // 处理slaughterPicture字段，它可能是数组或字符串
    if (Array.isArray(picturelist.slaughterPicture)) {
        // 如果直接是数组，直接返回
        return picturelist.slaughterPicture.filter(url => url && typeof url === 'string' && url.startsWith('http'))
    } else if (typeof picturelist.slaughterPicture === 'string') {
        // 如果是字符串，尝试解析
        return parseImageUrls(picturelist.slaughterPicture)
    }
    return []
}


const pictureDetail = () => {
    tread.get("http://localhost:5124/api/WriteBasic/GetPic", { params: { batch: batch.value } }).then((res) => {
        if (res.data.code == 200) {
            console.log('图片反填API响应:', res.data.data)

            // 处理API返回的数据
            const apiData = res.data.data

            // 确保cultivationPicture字段正确处理
            if (apiData.cultivationPicture) {
                if (Array.isArray(apiData.cultivationPicture)) {
                    // 如果API返回的是数组，直接使用
                    picturelist.cultivationPicture = apiData.cultivationPicture
                } else if (typeof apiData.cultivationPicture === 'string') {
                    // 如果是字符串，尝试解析为数组
                    try {
                        const parsed = JSON.parse(apiData.cultivationPicture)
                        picturelist.cultivationPicture = Array.isArray(parsed) ? parsed : [apiData.cultivationPicture]
                    } catch (e) {
                        // 如果解析失败，当作单个URL处理
                        picturelist.cultivationPicture = [apiData.cultivationPicture]
                    }
                }
            }

            // 确保aptitude字段正确处理
            if (apiData.aptitude) {
                if (Array.isArray(apiData.aptitude)) {
                    // 如果API返回的是数组，直接使用
                    picturelist.aptitude = apiData.aptitude
                } else if (typeof apiData.aptitude === 'string') {
                    // 如果是字符串，尝试解析为数组
                    try {
                        const parsed = JSON.parse(apiData.aptitude)
                        picturelist.aptitude = Array.isArray(parsed) ? parsed : [apiData.aptitude]
                    } catch (e) {
                        // 如果解析失败，当作单个URL处理
                        picturelist.aptitude = [apiData.aptitude]
                    }
                }
            }

            // 确保slaughterPicture字段正确处理
            if (apiData.slaughterPicture) {
                if (Array.isArray(apiData.slaughterPicture)) {
                    // 如果API返回的是数组，直接使用
                    picturelist.slaughterPicture = apiData.slaughterPicture
                } else if (typeof apiData.slaughterPicture === 'string') {
                    // 如果是字符串，尝试解析为数组
                    try {
                        const parsed = JSON.parse(apiData.slaughterPicture)
                        picturelist.slaughterPicture = Array.isArray(parsed) ? parsed : [apiData.slaughterPicture]
                    } catch (e) {
                        // 如果解析失败，当作单个URL处理
                        picturelist.slaughterPicture = [apiData.slaughterPicture]
                    }
                }
            }

            // 复制其他字段
            Object.assign(picturelist, {
                ...apiData,
                cultivationPicture: picturelist.cultivationPicture, // 使用处理后的cultivationPicture
                aptitude: picturelist.aptitude, // 使用处理后的aptitude
                slaughterPicture: picturelist.slaughterPicture // 使用处理后的slaughterPicture
            })

            console.log('处理后的picturelist:', picturelist)
        } else {
            console.error('获取图片信息失败:', res.data.message)
        }
    }).catch((error) => {
        console.error('获取图片信息出错:', error)
    })
}
const fantian = () => {
    dialogFormVisible.value = true;
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    form.picture = uploadFile.url!
    dialogFormVisible.value = true
}
// 保存养殖信息
const saveCultivationInfo = () => {
    console.log('保存养殖信息:', detail.value)
    // 这里可以添加保存到后端的逻辑
    ElMessage.success('养殖信息保存成功')
    dialogFormVisible.value = false
}
// 获取当前时间
const getCurrentTime = () => {
    const now = new Date()
    currentTime.value = now.toLocaleString('zh-CN')
}
//基本信息
const batch = ref(route.query.batch)
const Detail = () => {
    tread.get("/api/Basic/GetBasicDetail", { params: { batch: batch.value } }).then((res) => {
        if (res.data.code == 200) {
            Object.assign(form, res.data.data)
        } else {
            console.error('获取基本信息失败:', res.data.message)
        }
    }).catch((error) => {
        console.error('获取基本信息出错:', error)
    })
}
const ImmunityDetail = reactive({

    "rearingDays": "",
    "way": "",
    "function": "",
    "batch": ""
})

// 免疫信息行数据
const immunityRows = ref<any[]>([])

// 添加免疫信息行
const addImmunityRow = () => {
    const newRow = {
        id: 0, // 新增记录ID为0
        rearingDays: "",
        way: "",
        function: "",
        batch: batch.value || "" // 使用当前批次号
    }
    immunityRows.value.push(newRow)
    ElMessage.success('已添加新的免疫记录')
}

// 添加带示例数据的免疫信息行
const addImmunityRowWithSample = () => {
    const sampleData = [
        { rearingDays: "40", way: "巴二联苗", function: "皮下注射", batch: "SC006" },
        { rearingDays: "60", way: "三联疫苗", function: "肌肉注射", batch: "SC007" },
        { rearingDays: "30", way: "单联疫苗", function: "口服", batch: "SC008" }
    ]

    const randomSample = sampleData[Math.floor(Math.random() * sampleData.length)]
    immunityRows.value.push({ ...randomSample })
    ElMessage.success('已添加新的免疫记录（含示例数据）')
}

// 删除免疫信息行
const removeImmunityRow = (index: number) => {
    immunityRows.value.splice(index, 1)
    ElMessage.success('已删除免疫记录')
}

// 保存免疫信息行
const saveImmunityRow = (index: number) => {
    const row = immunityRows.value[index]
    console.log('保存免疫信息行:', index, row)

    // 这里可以添加保存到后端的逻辑
    // 例如：调用API保存数据
    // saveImmunityRowToServer(row)

    ElMessage.success(`免疫记录 ${index + 1} 已保存`)
}

// 保存单行免疫信息
const saveSingleImmunityRow = async (index: number) => {
    try {
        const row = immunityRows.value[index]

        // 数据验证
        if (!row) {
            ElMessage.error('数据不存在')
            return
        }

        if (!batch.value) {
            ElMessage.error('批次号不能为空')
            return
        }

        // 验证必填字段
        if (!row.rearingDays) {
            ElMessage.warning('养殖天数不能为空')
            return
        }
        if (!row.way) {
            ElMessage.warning('免疫方式不能为空')
            return
        }
        if (!row.function) {
            ElMessage.warning('免疫功能不能为空')
            return
        }
        if (!row.batch) {
            ElMessage.warning('批次号不能为空')
            return
        }

        console.log('=== 保存单行免疫信息开始 ===')
        console.log('行索引:', index)
        console.log('批次号:', batch.value)
        console.log('行数据:', row)

        // 构建请求数据 - 根据Swagger API格式
        const immunityModel = {
            id: row.id || 0, // 新增记录ID为0，更新记录使用实际ID
            isDeleted: false, // 新增记录默认为false
            rearingDays: parseInt(row.rearingDays) || 0,
            way: row.way,
            function: row.function,
            batch: row.batch
        }

        const requestData = {
            immunityModels: [immunityModel]
        }

        console.log('请求数据:', requestData)
        console.log('请求数据JSON:', JSON.stringify(requestData, null, 2))

        // 调用API保存单行数据
        const response = await twrite.post('/api/WriteCultivation/AddImmunity', requestData)

        console.log('API响应:', response)
        console.log('响应状态:', response.status)
        console.log('响应数据:', response.data)

        if (response.data && response.data.code === 200) {
            ElMessage.success(`免疫记录 ${index + 1} 保存成功`)
            // 更新本地数据中的ID（如果服务器返回了新的ID）
            if (response.data.data && response.data.data.length > 0) {
                row.id = response.data.data[0].id
            }
        } else {
            ElMessage.error('保存失败: ' + (response.data?.message || '服务器返回错误'))
        }
    } catch (error: any) {
        console.error('=== 保存单行免疫信息失败 ===')
        console.error('错误类型:', typeof error)
        console.error('错误对象:', error)
        console.error('错误响应:', error.response)
        console.error('错误消息:', error.message)

        if (error.response) {
            console.error('响应状态:', error.response.status)
            console.error('响应数据:', error.response.data)
            ElMessage.error('保存失败: ' + (error.response.data?.message || error.response.statusText))
        } else if (error.request) {
            ElMessage.error('保存失败: 网络连接错误')
        } else {
            ElMessage.error('保存失败: ' + error.message)
        }
    }
}

// 保存所有免疫信息到服务器
const saveAllImmunityRows = async () => {
    try {
        // 数据验证
        if (!batch.value) {
            ElMessage.error('批次号不能为空')
            return
        }

        if (!immunityRows.value || immunityRows.value.length === 0) {
            ElMessage.warning('没有免疫信息数据需要保存')
            return
        }

        // 验证每行数据
        for (let i = 0; i < immunityRows.value.length; i++) {
            const row = immunityRows.value[i]
            if (!row.rearingDays || !row.way || !row.function || !row.batch) {
                ElMessage.error(`第 ${i + 1} 行数据不完整，请检查所有字段`)
                return
            }
        }

        console.log('=== 保存所有免疫信息开始 ===')
        console.log('批次号:', batch.value)
        console.log('免疫行数据:', immunityRows.value)

        // 构建请求数据 - 根据Swagger API格式
        const immunityModels = immunityRows.value.map(row => ({
            id: row.id || 0, // 新增记录ID为0，更新记录使用实际ID
            isDeleted: false, // 新增记录默认为false
            rearingDays: parseInt(row.rearingDays) || 0,
            way: row.way,
            function: row.function,
            batch: row.batch
        }))

        const requestData = {
            immunityModels: immunityModels
        }

        console.log('请求数据:', requestData)
        console.log('请求数据JSON:', JSON.stringify(requestData, null, 2))

        // 调用API保存所有数据
        const response = await twrite.post('/api/WriteCultivation/AddImmunity', requestData)

        console.log('API响应:', response)
        console.log('响应状态:', response.status)
        console.log('响应数据:', response.data)

        if (response.data && response.data.code === 200) {
            ElMessage.success('所有免疫信息已保存')
            // 更新本地数据中的ID（如果服务器返回了新的ID）
            if (response.data.data && response.data.data.length > 0) {
                response.data.data.forEach((item: any, index: number) => {
                    if (immunityRows.value[index]) {
                        immunityRows.value[index].id = item.id
                    }
                })
            }
        } else {
            ElMessage.error('保存失败: ' + (response.data?.message || '服务器返回错误'))
        }
    } catch (error: any) {
        console.error('=== 保存所有免疫信息失败 ===')
        console.error('错误类型:', typeof error)
        console.error('错误对象:', error)
        console.error('错误响应:', error.response)
        console.error('错误消息:', error.message)

        if (error.response) {
            console.error('响应状态:', error.response.status)
            console.error('响应数据:', error.response.data)
            ElMessage.error('保存失败: ' + (error.response.data?.message || error.response.statusText))
        } else if (error.request) {
            ElMessage.error('保存失败: 网络连接错误')
        } else {
            ElMessage.error('保存失败: ' + error.message)
        }
    }
}

// 调试免疫数据
const debugImmunityData = () => {
    console.log('=== 调试免疫数据开始 ===')
    console.log('当前批次号:', batch.value)
    console.log('免疫行数据:', immunityRows.value)
    console.log('免疫行数据长度:', immunityRows.value.length)

    if (immunityRows.value.length > 0) {
        immunityRows.value.forEach((row, index) => {
            console.log(`第 ${index + 1} 行数据:`, row)
            console.log(`  养殖天数: ${row.rearingDays} (${typeof row.rearingDays})`)
            console.log(`  免疫方式: ${row.way} (${typeof row.way})`)
            console.log(`  免疫功能: ${row.function} (${typeof row.function})`)
            console.log(`  批次号: ${row.batch} (${typeof row.batch})`)
        })
    }

    // 测试构建请求数据
    if (immunityRows.value.length > 0) {
        const testRequestData = {
            command: "AddImmunity",
            batch: batch.value,
            immunityRows: immunityRows.value
        }
        console.log('测试请求数据:', testRequestData)
        console.log('测试请求数据JSON:', JSON.stringify(testRequestData, null, 2))
    }

    console.log('=== 调试免疫数据结束 ===')
    ElMessage.info('调试信息已输出到控制台')
}

//免疫信息

const Immunitylist = () => {
    console.log('正在获取免疫信息，batch:', batch.value);
    tread.get("/api/Cultivation/ImmunityDetail", { params: { batch: batch.value } }).then((res) => {
        console.log('免疫信息API响应:', res.data);
        if (res.data.code == 200) {
            console.log('免疫信息数据:', res.data.data);
            if (res.data.data) {
                // 将获取的数据添加到行数组中
                immunityRows.value = [res.data.data];
                console.log('赋值后的immunityRows数组:', immunityRows.value);
                ElMessage.success('免疫信息加载成功');
            } else {
                ElMessage.warning('暂无免疫信息数据');
            }
        } else {
            console.error('获取免疫信息失败:', res.data.message);
            ElMessage.error('获取免疫信息失败: ' + res.data.message);
        }
    }).catch((error) => {
        console.error('获取免疫信息出错:', error);
        ElMessage.error('获取免疫信息出错: ' + error.message);
    });
}
//养殖信息
const detail = ref({
    "variety": "",
    "source": "",
    "rearingDays": "",
    "brand": "",
    "rearingLeader": "",
    "outDate": "",
    "batch": route.query.batch,

})
const yangzhi = () => {
    previewVisible1.value = true;

}

const yangzhidetails = () => {
    console.log('正在获取养殖信息，batch:', batch.value)
    axios.get("http://localhost:5159/api/Cultivation/GetCultivation", { params: { batch: batch.value } }).then((res) => {
        console.log('API响应:', res.data)
        if (res.data.code == 200) {
            console.log('养殖信息数据:', res.data.data)
            // 确保数据正确赋值到响应式对象
            if (res.data.data) {
                // 使用Object.assign确保响应式更新
                Object.assign(detail.value, res.data.data)
                console.log('赋值后的detail对象:', detail.value)
                ElMessage.success('养殖信息加载成功')
            } else {
                ElMessage.warning('暂无养殖信息数据')
            }
        } else {
            console.error('获取养殖信息失败:', res.data.message)
            ElMessage.error('获取养殖信息失败: ' + res.data.message)
        }
    }).catch((error) => {
        console.error('获取养殖信息出错:', error)
        ElMessage.error('获取养殖信息出错: ' + error.message)
    })
}

// 测试数据方法
const testData = () => {
    console.log('测试数据绑定')
    detail.value = {
        "variety": "测试品种",
        "source": "测试来源",
        "rearingDays": "120",
        "brand": "测试品牌",
        "rearingLeader": "测试负责人",
        "outDate": "2024-01-01",
        "batch": batch.value,
    }
    ElMessage.success('测试数据已设置')
}

const form = reactive({
    id: '',
    "sid": '',
    "batch": "",
    "expiration": '',
    "license": "",
    "company": "",
    "picture": "",
    "inspectionReport": "",
    updator: stores.createApp.userName,
})

// 多图片上传相关变量
const inspectionReports = ref<any[]>([])
const uploadAction = ref('/api/upload/image')
const uploadHeaders = ref({
    'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
})

// 图片预览相关变量
const previewVisible = ref(false)
const currentImageIndex = ref(0)
const currentImageUrl = ref('')

// 触摸滑动相关变量
const touchStartX = ref(0)
const touchStartY = ref(0)
const touchEndX = ref(0)
const touchEndY = ref(0)

const lists = ref<any[]>([]);
const storelist = () => {
    tread.get("/api/Basic/StoreList", {}).then((res) => {
        console.log('商品列表数据:', res)
        if (res.data && res.data.data) {
            lists.value = res.data.data
        } else {
            console.error('商品列表数据格式错误:', res.data)
            ElMessage.error('商品列表加载失败')
        }
    }).catch((error) => {
        console.error('获取商品列表失败:', error)
        ElMessage.error('商品列表加载失败: ' + error.message)
    })
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    form.picture = response;
}

// 获取商品名称
const getProductName = () => {
    const selectedProduct = lists.value.find(item => item.id === form.sid)
    return selectedProduct ? selectedProduct.storeName : ''
}

// 上传前验证
const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt5M = file.size / 1024 / 1024 < 5

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过 5MB!')
        return false
    }
    return true
}

// 自定义上传处理
const customUpload = (options: any) => {
    const { file } = options

    // 直接使用本地预览，不依赖服务器上传
    const reader = new FileReader()
    reader.onload = (e) => {
        inspectionReports.value.push({
            url: e.target?.result as string,
            name: file.name,
            id: Date.now() + Math.random()
        })
        ElMessage.success('图片添加成功')
    }
    reader.readAsDataURL(file)
}

// 上传成功回调
const handleReportSuccess = (response: any, file: any) => {
    let imageUrl = ''
    if (response.code === 200) {
        imageUrl = response.data?.url || response.data
    } else if (response.url) {
        imageUrl = response.url
    } else if (typeof response === 'string') {
        imageUrl = response
    }

    if (imageUrl) {
        // 获取现有的图片URL数组
        const existingUrls = parseImageUrls(picturelist.report)

        // 添加新的图片URL
        existingUrls.push(imageUrl)

        // 更新picturelist.report字段
        picturelist.report = JSON.stringify(existingUrls)

        // 同时更新inspectionReports用于预览功能
        inspectionReports.value.push({
            url: imageUrl,
            name: file.name,
            id: Date.now() + Math.random()
        })

        ElMessage.success('图片上传成功')
    }
}

// 动检证上传成功回调
const handleInspectionSuccess = (response: any, file: any) => {
    let imageUrl = ''
    if (response.code === 200) {
        imageUrl = response.data?.url || response.data
    } else if (response.url) {
        imageUrl = response.url
    } else if (typeof response === 'string') {
        imageUrl = response
    }

    if (imageUrl) {
        // 获取现有的图片URL数组
        const existingUrls = parseImageUrls(picturelist.inspection)

        // 添加新的图片URL
        existingUrls.push(imageUrl)

        // 更新picturelist.inspection字段
        picturelist.inspection = JSON.stringify(existingUrls)

        ElMessage.success('动检证图片上传成功')
    }
}

// 企业照片上传成功回调
const handleCultivationSuccess = (response: any, file: any) => {
    let imageUrl = ''
    if (response.code === 200) {
        imageUrl = response.data?.url || response.data
    } else if (response.url) {
        imageUrl = response.url
    } else if (typeof response === 'string') {
        imageUrl = response
    }

    if (imageUrl) {
        // 确保cultivationPicture是数组格式
        if (!Array.isArray(picturelist.cultivationPicture)) {
            picturelist.cultivationPicture = []
        }

        // 添加新的图片URL到数组
        picturelist.cultivationPicture.push(imageUrl)

        ElMessage.success('企业照片上传成功')
    }
}

// 相关资质图片上传成功回调
const handleAptitudeSuccess = (response: any, file: any) => {
    let imageUrl = ''
    if (response.code === 200) {
        imageUrl = response.data?.url || response.data
    } else if (response.url) {
        imageUrl = response.url
    } else if (typeof response === 'string') {
        imageUrl = response
    }

    if (imageUrl) {
        // 确保aptitude是数组格式
        if (!Array.isArray(picturelist.aptitude)) {
            picturelist.aptitude = []
        }

        // 添加新的图片URL到数组
        picturelist.aptitude.push(imageUrl)

        ElMessage.success('相关资质图片上传成功')
    }
}

// 屠宰企业照片上传成功回调
const handleSlaughterPictureSuccess = (response: any, file: any) => {
    let imageUrl = ''
    if (response.code === 200) {
        imageUrl = response.data?.url || response.data
    } else if (response.url) {
        imageUrl = response.url
    } else if (typeof response === 'string') {
        imageUrl = response
    }

    if (imageUrl) {
        // 确保slaughterPicture是数组格式
        if (!Array.isArray(picturelist.slaughterPicture)) {
            picturelist.slaughterPicture = []
        }

        // 添加新的图片URL到数组
        picturelist.slaughterPicture.push(imageUrl)

        ElMessage.success('屠宰企业照片上传成功')
    }
}


// 预览图片
const previewImage = (index: number) => {
    const reportImages = getReportImages()
    if (index >= 0 && index < reportImages.length) {
        currentImageIndex.value = index
        currentImageUrl.value = reportImages[index]
        previewVisible.value = true
    }
}

// 上一张图片
const prevImage = () => {
    const reportImages = getReportImages()
    if (currentImageIndex.value > 0) {
        currentImageIndex.value--
        currentImageUrl.value = reportImages[currentImageIndex.value]
    }
}

// 下一张图片
const nextImage = () => {
    const reportImages = getReportImages()
    if (currentImageIndex.value < reportImages.length - 1) {
        currentImageIndex.value++
        currentImageUrl.value = reportImages[currentImageIndex.value]
    }
}

// 跳转到指定图片
const goToImage = (index: number) => {
    const reportImages = getReportImages()
    if (index >= 0 && index < reportImages.length) {
        currentImageIndex.value = index
        currentImageUrl.value = reportImages[index]
    }
}

// 触摸开始
const handleTouchStart = (e: TouchEvent) => {
    touchStartX.value = e.touches[0].clientX
    touchStartY.value = e.touches[0].clientY
}

// 触摸移动
const handleTouchMove = (e: TouchEvent) => {
    e.preventDefault() // 防止页面滚动
}

// 触摸结束
const handleTouchEnd = (e: TouchEvent) => {
    touchEndX.value = e.changedTouches[0].clientX
    touchEndY.value = e.changedTouches[0].clientY
    handleSwipe()
}

// 处理滑动
const handleSwipe = () => {
    const deltaX = touchEndX.value - touchStartX.value
    const deltaY = touchEndY.value - touchStartY.value

    // 判断是否为水平滑动
    if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
        if (deltaX > 0) {
            // 右滑 - 上一张图片
            prevImage()
        } else {
            // 左滑 - 下一张图片
            nextImage()
        }
    }
}

// 移除检验报告
const removeReport = (index: number) => {
    // 获取现有的图片URL数组
    const existingUrls = parseImageUrls(picturelist.report)

    // 从数组中移除指定索引的图片
    if (index >= 0 && index < existingUrls.length) {
        existingUrls.splice(index, 1)

        // 更新picturelist.report字段
        picturelist.report = existingUrls.length > 0 ? JSON.stringify(existingUrls) : ""
    }

    // 同时更新inspectionReports用于预览功能
    inspectionReports.value.splice(index, 1)
    ElMessage.success('已移除检验报告')

    // 如果删除的是当前预览的图片，调整索引
    if (index === currentImageIndex.value) {
        if (inspectionReports.value.length === 0) {
            previewVisible.value = false
        } else if (currentImageIndex.value >= inspectionReports.value.length) {
            currentImageIndex.value = inspectionReports.value.length - 1
            currentImageUrl.value = inspectionReports.value[currentImageIndex.value].url
        }
    } else if (index < currentImageIndex.value) {
        currentImageIndex.value--
    }
}

// 删除动检证图片
const removeInspectionImage = (index: number) => {
    // 获取现有的图片URL数组
    const existingUrls = parseImageUrls(picturelist.inspection)

    // 从数组中移除指定索引的图片
    if (index >= 0 && index < existingUrls.length) {
        existingUrls.splice(index, 1)

        // 更新picturelist.inspection字段
        picturelist.inspection = existingUrls.length > 0 ? JSON.stringify(existingUrls) : ""
    }

    ElMessage.success('已移除动检证图片')
}

// 预览动检证图片
const previewInspectionImage = (index: number) => {
    const inspectionImages = getInspectionImages()
    if (index >= 0 && index < inspectionImages.length) {
        currentImageIndex.value = index
        currentImageUrl.value = inspectionImages[index]
        previewVisible.value = true
    }
}

// 删除企业照片
const removeCultivationImage = (index: number) => {
    // 确保cultivationPicture是数组格式
    if (Array.isArray(picturelist.cultivationPicture)) {
        // 从数组中移除指定索引的图片
        if (index >= 0 && index < picturelist.cultivationPicture.length) {
            picturelist.cultivationPicture.splice(index, 1)
        }
    } else {
        // 如果是字符串格式，转换为数组处理
        const existingUrls = parseImageUrls(picturelist.cultivationPicture)
        if (index >= 0 && index < existingUrls.length) {
            existingUrls.splice(index, 1)
            picturelist.cultivationPicture = existingUrls
        }
    }

    ElMessage.success('已移除企业照片')
}

// 删除相关资质图片
const removeAptitudeImage = (index: number) => {
    // 确保aptitude是数组格式
    if (Array.isArray(picturelist.aptitude)) {
        // 从数组中移除指定索引的图片
        if (index >= 0 && index < picturelist.aptitude.length) {
            picturelist.aptitude.splice(index, 1)
        }
    } else {
        // 如果是字符串格式，转换为数组处理
        const existingUrls = parseImageUrls(picturelist.aptitude)
        if (index >= 0 && index < existingUrls.length) {
            existingUrls.splice(index, 1)
            picturelist.aptitude = existingUrls
        }
    }

    ElMessage.success('已移除相关资质图片')
}

// 删除屠宰企业照片
const removeSlaughterPictureImage = (index: number) => {
    // 确保slaughterPicture是数组格式
    if (Array.isArray(picturelist.slaughterPicture)) {
        // 从数组中移除指定索引的图片
        if (index >= 0 && index < picturelist.slaughterPicture.length) {
            picturelist.slaughterPicture.splice(index, 1)
        }
    } else {
        // 如果是字符串格式，转换为数组处理
        const existingUrls = parseImageUrls(picturelist.slaughterPicture)
        if (index >= 0 && index < existingUrls.length) {
            existingUrls.splice(index, 1)
            picturelist.slaughterPicture = existingUrls
        }
    }

    ElMessage.success('已移除屠宰企业照片')
}

// 预览屠宰企业照片
const previewSlaughterPictureImage = (index: number) => {
    const slaughterPictureImages = getSlaughterPictureImages()
    if (index >= 0 && index < slaughterPictureImages.length) {
        currentImageIndex.value = index
        currentImageUrl.value = slaughterPictureImages[index]
        previewVisible.value = true
    }
}

// 预览企业照片
const previewCultivationImage = (index: number) => {
    const cultivationImages = getCultivationImages()
    if (index >= 0 && index < cultivationImages.length) {
        currentImageIndex.value = index
        currentImageUrl.value = cultivationImages[index]
        previewVisible.value = true
    }
}

// 预览相关资质图片
const previewAptitudeImage = (index: number) => {
    const aptitudeImages = getAptitudeImages()
    if (index >= 0 && index < aptitudeImages.length) {
        currentImageIndex.value = index
        currentImageUrl.value = aptitudeImages[index]
        previewVisible.value = true
    }
}

// 下载图片
const downloadImage = () => {
    if (currentImageUrl.value) {
        const link = document.createElement('a')
        link.href = currentImageUrl.value
        link.download = `检验报告_${currentImageIndex.value + 1}.png`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        ElMessage.success('图片下载成功')
    }
}

// 保存表单数据
const handleSave = () => {
    console.log('保存表单数据:', form)
    twrite.post("/api/WriteBasic/UpdateBasic", form).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success(res.data.message || '保存成功')
        } else {
            ElMessage.error(res.data.message || '保存失败')
        }
    }).catch((error) => {
        console.error('保存失败:', error)
        ElMessage.error('保存失败: ' + error.message)
    })
}

// 获取商品详情
// const getProductDetail = async () => {
//     const productId = route.params.id
//     if (!productId) {
//         ElMessage.error('商品ID不存在')
//         return
//     }

//     try {
//         const res = await read.get(`/api/Basic/GetBasicById/${productId}`)
//         if (res.data && res.data.code === 200) {
//             productData.value = res.data.data
//         } else {
//             ElMessage.error('获取商品信息失败')
//         }
//     } catch (error) {
//         console.error('获取商品详情失败:', error)
//         ElMessage.error('获取商品信息失败')
//     }
// }


</script>

<style scoped>
.traceability-detail-container {
    min-height: 100vh;
    background-color: #f5f7fa;
    padding: 0;
}

.main-content {
    display: flex;
    gap: 20px;
    width: 100%;
    margin: 0;
    position: relative;
}

/* 右上角操作按钮区域 */
.top-right-actions {
    position: absolute;
    top: 20px;
    right: 20px;
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    z-index: 10;
}

/* 左侧商品信息区域 */
.product-section {
    flex: 1;
    background: white;
    border-radius: 0;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin: 0;
    width: 100%;
}

.product-image-container {
    position: relative;
    width: 200px;
    height: 200px;
    margin-bottom: 20px;
}

.product-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
}

.product-logo {
    position: absolute;
    top: 8px;
    left: 8px;
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.9);
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
}

.logo-icon {
    margin-right: 4px;
    font-size: 14px;
}

.product-info {
    margin-bottom: 24px;
}

.product-name {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 16px 0;
}

.product-details {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.detail-item {
    display: flex;
    font-size: 14px;
}

.detail-label {
    color: #606266;
    min-width: 120px;
    margin-right: 8px;
}

.detail-value {
    color: #303133;
    font-weight: 500;
}

/* 产品检验报告区域 */
.inspection-reports {
    margin-bottom: 24px;
}


.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0;
}

.reports-container {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    align-items: flex-start;
}

.report-item {
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.report-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.report-thumbnail {
    width: 100%;
    height: 100%;
    object-fit: cover;
    cursor: pointer;
}

.remove-icon {
    position: absolute;
    top: 8px;
    right: 8px;
    font-size: 16px;
    color: #f56c6c;
    cursor: pointer;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    padding: 4px;
    transition: all 0.3s ease;
}

.remove-icon:hover {
    background: #f56c6c;
    color: white;
    transform: scale(1.1);
}

.report-placeholder {
    width: 200px;
    height: 200px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background: #fafafa;
    transition: all 0.3s ease;
}

.report-placeholder:hover {
    border-color: #409eff;
    background: #f0f9ff;
}

.add-icon {
    font-size: 48px;
    color: #d9d9d9;
    margin-bottom: 8px;
}

.report-placeholder:hover .add-icon {
    color: #409eff;
}

/* 上传组件样式 */
.report-uploader {
    display: inline-block;
}

.report-uploader .el-upload {
    display: block;
}

/* 图片预览样式 */
.image-preview-container {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 400px;
    background: #f5f7fa;
    border-radius: 8px;
    overflow: hidden;
}

.image-display-area {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.preview-image {
    max-width: 100%;
    max-height: 400px;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    user-select: none;
    -webkit-user-select: none;
}

/* 导航箭头 */
.nav-arrow {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 40px;
    height: 40px;
    background: rgba(0, 0, 0, 0.5);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
    z-index: 10;
}

.nav-arrow:hover {
    background: rgba(0, 0, 0, 0.7);
    transform: translateY(-50%) scale(1.1);
}

.nav-arrow.disabled {
    opacity: 0.3;
    cursor: not-allowed;
}

.nav-arrow.disabled:hover {
    background: rgba(0, 0, 0, 0.5);
    transform: translateY(-50%) scale(1);
}

.nav-left {
    left: 20px;
}

.nav-right {
    right: 20px;
}

/* 分页指示器 */
.pagination-dots {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
    margin-top: 20px;
}

.dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #d9d9d9;
    cursor: pointer;
    transition: all 0.3s ease;
}

.dot.active {
    background: #409eff;
    transform: scale(1.2);
}

.dot:hover {
    background: #409eff;
    opacity: 0.7;
}

.dialog-footer {
    text-align: center;
}

/* 缩略图样式优化 */
.report-thumbnail {
    width: 100%;
    height: 100%;
    object-fit: cover;
    cursor: pointer;
    transition: opacity 0.3s ease;
}

.report-thumbnail:hover {
    opacity: 0.8;
}

/* 操作按钮区域 */
.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    align-items: center;
}

.action-btn {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.action-icon {
    color: #f39c12 !important;
    font-size: 14px;
}

/* 按钮特殊样式 */
.action-btn.el-button--danger {
    background: linear-gradient(135deg, #ff6b6b, #ee5a52);
    border: none;
}

.action-btn.el-button--primary {
    background: linear-gradient(135deg, #409eff, #36a3f7);
    border: none;
}

/* 右侧表单区域 */
.form-section {
    width: 400px;
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    height: fit-content;
}

.detail-form {
    width: 100%;
}

.detail-form .el-form-item {
    margin-bottom: 20px;
}

.detail-form .el-form-item__label {
    font-weight: 500;
    color: #606266;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.avatar-uploader:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}

.avatar {
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 6px;
}

/* 底部卡片组件样式 */
.bottom-card {
    width: 100%;
    height: calc(100vh - 200px);
    background: white;
    border-radius: 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin: 15px 0 0 0;
    display: flex;
    flex-direction: column;
}

.bottom-card .card-header {
    padding: 16px 24px;
    border-bottom: 1px solid #e4e7ed;
    background: #f8f9fa;
    flex-shrink: 0;
}

.bottom-card .card-title {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.bottom-card .card-content {
    padding: 24px;
    flex: 1;
    display: flex;
    flex-direction: column;
}

/* 状态指示器 */
.status-indicators {
    display: flex;
    gap: 20px;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e4e7ed;
}

.status-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
}

.status-item.completed {
    background: #f0f9ff;
    color: #0369a1;
    border: 1px solid #bae6fd;
}

.status-item.incomplete {
    background: #fef3c7;
    color: #d97706;
    border: 1px solid #fde68a;
}

.status-item.active {
    background: #dbeafe;
    color: #1d4ed8;
    border: 2px solid #3b82f6;
    font-weight: 600;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
}

/* 不同颜色的未完成状态 */
.status-item.incomplete.breeding {
    background: #fef2f2;
    color: #dc2626;
    border: 1px solid #fecaca;
}

.status-item.incomplete.slaughter {
    background: #f0f9ff;
    color: #2563eb;
    border: 1px solid #bfdbfe;
}

.status-item.incomplete.processing {
    background: #f0fdf4;
    color: #16a34a;
    border: 1px solid #bbf7d0;
}

.status-icon {
    font-size: 16px;
}

/* 主内容网格 */
.main-content-grid {
    display: flex;
    flex-direction: column;
    gap: 20px;
    flex: 1;
    min-height: 400px;
}

.left-column {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

/* 信息区域 */
.info-section {
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: #f8f9fa;
    border-bottom: 1px solid #e4e7ed;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 16px;
}

.add-row-text {
    color: #409eff;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    padding: 4px 8px;
    border-radius: 4px;
    transition: all 0.3s ease;
    border: 1px solid #409eff;
    background: #f0f9ff;
}

.add-row-text:hover {
    background: #409eff;
    color: white;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

.add-sample-text {
    color: #67c23a;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    padding: 4px 8px;
    border-radius: 4px;
    transition: all 0.3s ease;
    border: 1px solid #67c23a;
    background: #f0f9ff;
}

.add-sample-text:hover {
    background: #67c23a;
    color: white;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(103, 194, 58, 0.3);
}

.section-title {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
}

.settings-btn {
    padding: 4px 12px;
    font-size: 12px;
}

.settings-btn .el-icon {
    margin-right: 4px;
}

.section-content {
    padding: 16px;
    min-height: 60px;
    display: flex;
    align-items: center;
}

/* 上传区域 */
.upload-area {
    display: flex;
    align-items: center;
    gap: 12px;
}

.upload-placeholder {
    width: 80px;
    height: 60px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fafafa;
    cursor: pointer;
    transition: all 0.3s ease;
}

.upload-placeholder:hover {
    border-color: #409eff;
    background: #f0f9ff;
}

.upload-icon {
    font-size: 24px;
    color: #d9d9d9;
}

/* 养殖信息内容样式 */
.cultivation-info {
    width: 100%;
    padding: 16px 0;
}


/* 免疫信息内容样式 */
.immunity-info {
    width: 100%;
    padding: 16px 0;
}

.immunity-rows {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.immunity-row {
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.immunity-row:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    transform: translateY(-1px);
}

.row-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;
}

.row-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.remove-row-btn {
    padding: 4px 8px;
    font-size: 12px;
}

.immunity-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    width: 100%;
}

.immunity-item {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border: 1px solid #bae6fd;
    border-radius: 8px;
    padding: 16px;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.immunity-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(135deg, #0ea5e9, #3b82f6);
    border-radius: 0 2px 2px 0;
}

.immunity-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(14, 165, 233, 0.15);
    border-color: #0ea5e9;
}

.immunity-label {
    font-size: 12px;
    font-weight: 600;
    color: #0369a1;
    margin-bottom: 8px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.immunity-label::before {
    content: '💉';
    font-size: 10px;
}

.immunity-value {
    font-size: 14px;
    font-weight: 600;
    color: #0c4a6e;
    line-height: 1.4;
    word-break: break-word;
}

/* 输入框样式 */
.immunity-value .el-input {
    width: 100%;
}

.immunity-value .el-input__wrapper {
    background: transparent;
    border: none;
    box-shadow: none;
    padding: 0;
}

.immunity-value .el-input__inner {
    background: transparent;
    border: none;
    padding: 0;
    font-size: 14px;
    font-weight: 600;
    color: #0c4a6e;
    text-align: left;
}

.immunity-value .el-input__inner:focus {
    background: rgba(14, 165, 233, 0.1);
    border-radius: 4px;
    padding: 4px 8px;
    margin: -4px -8px;
}

.immunity-value .el-input__inner::placeholder {
    color: #9ca3af;
    font-weight: 400;
}

/* 无数据状态 */
.no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    color: #9ca3af;
}

.no-data-icon {
    font-size: 48px;
    margin-bottom: 12px;
    opacity: 0.5;
}

.no-data-text {
    font-size: 14px;
    font-weight: 500;
}

/* 信息网格布局 */
.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    width: 100%;
}

.info-item {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 16px;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.info-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(135deg, #409eff, #67c23a);
    border-radius: 0 2px 2px 0;
}

.info-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-color: #409eff;
}

.info-label {
    font-size: 12px;
    font-weight: 600;
    color: #606266;
    margin-bottom: 8px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.info-label::before {
    content: '●';
    color: #409eff;
    font-size: 8px;
}

.info-value {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    line-height: 1.4;
    word-break: break-word;
}

/* 特殊样式优化 */
.info-item:nth-child(1) .info-label::before {
    color: #e74c3c;
}

.info-item:nth-child(2) .info-label::before {
    color: #3498db;
}

.info-item:nth-child(3) .info-label::before {
    color: #f39c12;
}

.info-item:nth-child(4) .info-label::before {
    color: #9b59b6;
}

.info-item:nth-child(5) .info-label::before {
    color: #1abc9c;
}

.info-item:nth-child(6) .info-label::before {
    color: #e67e22;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .info-grid {
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 12px;
    }

    .info-item {
        padding: 12px;
    }

    .info-label {
        font-size: 11px;
    }

    .info-value {
        font-size: 13px;
    }

    /* 免疫信息响应式 */
    .immunity-grid {
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 12px;
    }

    .immunity-item {
        padding: 12px;
    }

    .immunity-label {
        font-size: 11px;
    }

    .immunity-value {
        font-size: 13px;
    }

    /* 免疫信息行响应式 */
    .immunity-rows {
        gap: 16px;
    }

    .immunity-row {
        padding: 12px;
    }

    .row-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .row-title {
        font-size: 14px;
    }

    .remove-row-btn {
        align-self: flex-end;
    }

    /* 输入框移动端样式 */
    .immunity-value .el-input__inner {
        font-size: 13px;
    }

    .immunity-value .el-input__inner:focus {
        padding: 2px 4px;
        margin: -2px -4px;
    }
}

@media (max-width: 480px) {
    .info-grid {
        grid-template-columns: 1fr;
        gap: 8px;
    }

    .immunity-grid {
        grid-template-columns: 1fr;
        gap: 8px;
    }
}


.bottom-card .info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 16px;
    width: 100%;
}

.bottom-card .info-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: #f8f9fa;
    border-radius: 6px;
    border-left: 4px solid #409eff;
}

.bottom-card .info-label {
    font-weight: 500;
    color: #606266;
    min-width: 80px;
    margin-right: 12px;
}

.bottom-card .info-value {
    color: #303133;
    font-weight: 500;
}

.bottom-card .status-active {
    color: #67c23a;
    font-weight: 600;
}

/* 养殖信息和屠宰信息区域样式 */
.breeding-section,
.slaughter-section {
    width: 100%;
    margin-bottom: 20px;
}

.breeding-section {
    border-left: 4px solid #e74c3c;
    padding-left: 16px;
}

.slaughter-section {
    border-left: 4px solid #3498db;
    padding-left: 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .main-content {
        flex-direction: column;
    }

    .form-section {
        width: 100%;
    }
}

@media (max-width: 768px) {
    .traceability-detail-container {
        padding: 0;
    }

    .product-section {
        padding: 16px;
        border-radius: 0;
    }

    .product-image-container {
        width: 150px;
        height: 150px;
    }

    .action-buttons {
        flex-direction: column;
    }

    .action-btn {
        width: 100%;
        justify-content: center;
    }

    /* 右上角按钮响应式 */
    .top-right-actions {
        position: static;
        width: 100%;
        justify-content: center;
        margin-bottom: 16px;
    }

    .report-item,
    .report-placeholder {
        width: 150px;
        height: 150px;
    }

    .add-icon {
        font-size: 24px;
    }

    .bottom-card {
        height: calc(100vh - 150px);
        margin: 15px 0 0 0;
    }

    .bottom-card .card-header {
        padding: 12px 16px;
    }

    .bottom-card .card-content {
        padding: 16px;
    }

    .bottom-card .info-grid {
        grid-template-columns: 1fr;
        gap: 12px;
    }

    .bottom-card .info-item {
        padding: 10px 12px;
    }

    /* 移动端底部卡片样式调整 */
    .status-indicators {
        flex-direction: column;
        gap: 10px;
    }
}
</style>